package com.it.cloud.config.es;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.network.InetAddresses;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author yangyang7_kzx
 * @date 2019/11/26 17:36
 * @description
 */
@Slf4j
@Configuration
public class EsConfig {

    @Value("${es.cluster-name}")
    private String clusterName;

    @Value("${es.ip}")
    private String ips;

    @Value("${es.port}")
    private String port;

    @Bean("dataClient")
    public TransportClient getTransPortClient() {
        TransportClient client = null;
        Settings settings = Settings.builder()
                // 集群名, 如果你需要更改集群名（默认是elasticsearch）
                .put("cluster.name", clusterName)
                // 设置client.transport.sniff为true来使客户端去嗅探整个集群的状态，
                // 把集群中其它机器的ip地址加到客户端中。这样做的好处是，一般你不用手动
                // 设置集群里所有集群的ip到连接客户端，它会自动帮你添加，并且自动发现新加入集群的机器。
                .put("client.transport.sniff", false)
                .build();

        String[] ipArray = ips.split(",");
        try {
            client = new PreBuiltTransportClient(settings);
            for (String ip : ipArray) {//添加集群IP列表
                TransportAddress transportAddress = new InetSocketTransportAddress(InetAddresses.forString(ip), Integer.parseInt(port));
                client.addTransportAddresses(transportAddress);
            }
        } catch (Exception e) {
            log.error("create es client error:{}", e);
            if (client != null) {
                client.close();
            }
        }
        return client;
    }

}
